﻿using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace InfrastructureBase.Base.AuthBase.CustomAuth
{
    /// <summary>
    /// 动态添加 Policy
    /// </summary>
    public class AuthorizationPolicyProvider:DefaultAuthorizationPolicyProvider, IAuthorizationPolicyProvider
    {
        public AuthorizationPolicyProvider(IOptions<AuthorizationOptions> options) : base(options) { }

        public new Task<AuthorizationPolicy> GetDefaultPolicyAsync()
        => base.GetDefaultPolicyAsync();

        public new Task<AuthorizationPolicy?> GetFallbackPolicyAsync()
            => base.GetFallbackPolicyAsync();

        public new Task<AuthorizationPolicy?> GetPolicyAsync(string policyName)
        {
            if (policyName.StartsWith("User"))
            {
                var policy = new AuthorizationPolicyBuilder(JwtBearerDefaults.AuthenticationScheme);
                policy.AddRequirements(new CustomAuthorizationRequirement(policyName));
                return Task.FromResult<AuthorizationPolicy?>(policy.Build());
            }
            return base.GetPolicyAsync(policyName);
        }
    }
}
